package com.chromatic.competition.adapter;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.chromatic.competition.R;
import com.chromatic.competition.model.Friend;
import com.chromatic.competition.view.notifications.ChatActivity;

import java.util.ArrayList;
import java.util.List;

public class FriendsAdapter extends RecyclerView.Adapter<FriendsAdapter.FriendViewHolder>{
    private List<Friend> friends = new ArrayList<>();

    // 创建FriendViewHolder对象
    @NonNull
    @Override
    public FriendViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 加载布局文件friend_item.xml来创建View对象
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.friend_item, parent, false);
        // 返回FriendViewHolder对象
        return new FriendViewHolder(view);
    }
    // 绑定数据到FriendViewHolder
    @Override
    public void onBindViewHolder(@NonNull FriendViewHolder holder, int position) {
        // 获取当前位置的Friend对象
        Friend friend = friends.get(position);
        // 设置显示昵称的TextView的文本为Friend对象的昵称
        holder.nameTextView.setText(friend.getNickname());
        // 设置显示最后一条消息的TextView的文本为Friend对象的最后一条消息
        holder.lastMessageTextView.setText(friend.getLastMessage());

        // 设置点击监听器
        // 当用户点击列表项时，启动聊天页面，并将好友的ID传递给ChatActivity
        holder.itemView.setOnClickListener(v -> {
            // 创建一个Intent对象，用于启动ChatActivity
            Intent intent = new Intent(v.getContext(), ChatActivity.class);
            // 将friend_id作为额外数据传递给ChatActivity
            intent.putExtra("friend_id", friend.getFriendId());
            // 启动ChatActivity
            v.getContext().startActivity(intent);
        });
    }
    // 返回列表项数量
    @Override
    public int getItemCount() {
        return friends.size();
    }

    // 设置Friend列表数据
    @SuppressLint("NotifyDataSetChanged")
    public void setFriends(List<Friend> friends) {
        // 将传入的Friend列表赋值给成员变量friends
        this.friends = friends;
        // 通知RecyclerView数据集已更改
        notifyDataSetChanged();
    }

    // 定义FriendViewHolder内部类
    static class FriendViewHolder extends RecyclerView.ViewHolder {
        TextView nameTextView;
        TextView lastMessageTextView;

        // 构造方法用于初始化视图组件
        FriendViewHolder(@NonNull View itemView) {
            super(itemView);
            // 根据itemView查找并初始化nameTextView和lastMessageTextView
            nameTextView = itemView.findViewById(R.id.nameTextView);
            lastMessageTextView = itemView.findViewById(R.id.lastMessageTextView);
        }
    }
}
